package com.leshua.channel.mpos.common.exception;


import com.leshua.channel.mpos.common.enums.ErrorEnum;
import com.leshua.channel.mpos.dto.CommonRespDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Devlin
 * @date 2019/12/5
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理自定义的业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public CommonRespDto bizExceptionHandler(BusinessException e) {
        log.info("捕获业务异常！", e);
        return new CommonRespDto(e.getCode(), e.getMessage());
    }

    /**
     * spring mvc 校验异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public CommonRespDto validException(MethodArgumentNotValidException e) {
        FieldError fieldError = e.getBindingResult().getFieldError();
        assert fieldError != null;
        log.warn(fieldError.getField() + ":" + fieldError.getDefaultMessage());
        return new CommonRespDto(ErrorEnum.REQUEST_PARAM_INVALID.getCode(), fieldError.getDefaultMessage());
    }

    /**
     * 处理其他异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonRespDto exceptionHandler(Exception e) {
        log.error("捕获未知异常!:", e);
        return new CommonRespDto(ErrorEnum.SYSTEM_ERROR.getCode(), ErrorEnum.SYSTEM_ERROR.getMessage());
    }
}
